import QueryMaterial3 from "@/components/QueryMaterial3";
import { s_createProduceAlloc, s_getcommontableinfo, s_getProduceInfo, s_getSelectData, s_operateInfo, s_produce_updateInfo, s_purchase_updateInfo, s_stockOut, s_updateInfo, status2text } from "@/services/basis";
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormDateRangePicker, ProFormDigit, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProFormTextArea, ProTable } from "@ant-design/pro-components";
import { Button, Col, Drawer, Modal, Row, Space ,Image, message, Splitter, List, Divider, Tag, Typography, QRCode} from "antd";
import moment from "moment";
import printJS from "print-js";
import { useEffect, useRef, useState } from "react";
import { act } from "react-dom/test-utils";

//工序卡片打印模板--单个
function PrintTaskCard(props:any){
    // const [pic,setPic]=useState(props.fdata.pic?"/basis_api/file/get?filename="+props.fdata.pic:'');
    const [pic,setPic]=useState("/basis_api/file/get2?filename="+props.fdata.code);
    interface DataType{
      code?:string,name?:string,pic?:string,
      invstd?:string,invstd2?:string,munit_name?:string,
      quantity?:number,quantity_stock?:string,
    };
    const columns:ProColumns<DataType>[]=[
       {dataIndex:'pic',title:'图片' ,editable:false,width:60,
      //     render:(text:any)=>{
      //         var pic=text=="-"||text==undefined||text==false||text==null?'':"/basis_api/file/get?filename="+text.toString();
      //         return <Image src={pic}  
      //                style={{width:50,height:50}} alt='无' />
      //    },
      //  },
           render:(text,record,index,k)=>{
                         var pic="/basis_api/file/get2?filename="+record.code;
                         return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
      }},
       {dataIndex:'code',title:'编码',width:80},{dataIndex:'name',title:'名称',width:200,},
      {dataIndex:'invstd',title:'包装规格',width:200,},
      // {dataIndex:'invstd2',title:'型号',width:100,},
      {dataIndex:'munit_name',title:'单位',width:60},
      {dataIndex:'quantity',title:'需求数量',width:80,valueType:'digit'},
      {dataIndex:'quantity_stock',title:'库存数量',width:80,valueType:'digit'},
    ];
    
    return(
    <> 
                 <ProForm submitter={false}  style={{fontSize:11}}
                       layout="horizontal" labelAlign="left" labelCol={{offset:0,span:8}} labelWrap
                       initialValues={{...props.fdata}}
                       >
                      <Row  >
                        <Col span={2}>
                           <QRCode  value={props.fdata.taskcard_sno} size={150} />
                        </Col>
                         
                         <Col span={3}>
                             <ProFormText name='produce_vouch_code' label='内部备料单号' 
                             fieldProps={{style:{border:0}}} allowClear={false}   />
                             <ProFormText name='code' label='产品SKU'
                             fieldProps={{style:{border:0}}} allowClear={false}     
                             />
                              
                              {/* <ProFormText name='munit_name' label='单位'  width={120}/> */}
                              
                         </Col>
                         <Col span={4}>
                             <ProFormText name='taskcard_sno' label='工序卡号' 
                             fieldProps={{style:{border:0}}} allowClear={false} 
                               />
                              <ProFormText name='card_name' label='工序名称'
                              fieldProps={{style:{border:0}}} allowClear={false}  />
                              
                              {/* <ProFormText name='workcenter_name' label='生产中心'  width={120}/>
                              <ProFormText name='workgroup_name' label='工作组'  width={120}/> */}
                           </Col>
                           <Col span={3}>
                              {/* <ProFormDatePicker name='begindate' label='计划开始日期'  width={120} bordered={false}/> */}
                              <ProFormDatePicker name='enddate' label='计划完成日期'  
                              fieldProps={{style:{border:0}}} allowClear={false} />
                              <ProFormText name='quantity' label='生产数量' 
                              fieldProps={{style:{border:0}}} allowClear={false} />
                         </Col>
                         <Col span={2}>
                              {/* <ProFormText name='custom_name' label='店铺'  width={120}/>
                              <ProFormText name='prepare_vouch_code' label='配货单号'  width={120}/> */}
                              
                              {/* <ProFormText name='sale_vouch_code' label='申报单号'  width={120}/> */}
                              <Image src={pic} style={{width:120,height:120}} alt='NONE' />
                         </Col>
                      </Row>
                      <Row gutter={8}>
                        <Col span={7}>
                            <ProFormText name='name' label='产品名称' 
                            fieldProps={{style:{border:0}}} allowClear={false} labelCol={{offset:0,span:4}} />
                        </Col>
                        <Col span={7}>
                            <ProFormText name='invstd' label='包装规格' 
                            fieldProps={{style:{border:0}}} allowClear={false} labelCol={{offset:0,span:3}} />
                        </Col>
                      </Row>
                      <Row  >
                        <Col span={14}>
                        <ProTable<DataType>
                        dataSource={props.tdata}
                        rowKey='code'
                        columns={columns}
                        // scroll={{y:600}}
                       
                        options={false}
                        search={false}
                        bordered
                        columnEmptyText={false}
                        
                       />
                        </Col>
                      </Row>
                      
                </ProForm>
    </>)
};

const App:React.FC=()=>{
     const [openSale,setOpenSale]=useState(false);
     const [openQuery,setOpenQuery]=useState(false);
     const [newOrder,setNewOrder]=useState([]);//新增生产申报单的数据源
     const [etype,setEtype]=useState(1);//新增1，编辑0
     const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);//主界面要选择的行
     const [selectedOrder,setSelectedOrder]=useState({});//主界面选择编辑的申报单

     const [selectedQuery,setSelectedQuery]=useState<any[]>([]);

    //  const [tdata,setTdata]=useState([]);
    //申报单主表引用
    const formRef_main=useRef<ProFormInstance>();
    const actionRef_main=useRef<ActionType>();

     //查询店铺申报单条件
     const formRef_query=useRef<ProFormInstance>();
     const action_ref_query=useRef<ActionType>();
     const editable_ref_query=useRef<EditableFormInstance>();
     
    //  新增申报单引用
     const formRef_add=useRef<ProFormInstance>();
     const editable_ref_add=useRef<EditableFormInstance>();
     const action_ref_add=useRef<ActionType>();

     //生产分派
     const [openProduce,setOpenProduce]=useState(false);
     const [selectedPlanRecord,setSelectedPlanRecord]=useState<any[]>([]);
     const editableRef_main=useRef<EditableFormInstance>();
     const [material,setMaterial]=useState([]);
     const form_refProduce=useRef<ProFormInstance>();
     const editable_refProduce=useRef<EditableFormInstance>();
     const action_refProduce=useRef<ActionType>();
     const editable_refProduce2=useRef<EditableFormInstance>();//明细表
     const action_refProduce2=useRef<ActionType>();//明细表
     const [produceCard,setProduceCard]=useState<any[]>([]);
     const [selectedCard,setSelectedCard]=useState(0);//选中的工序卡片ID
     const form_refCaculate=useRef<ProFormInstance>();
     const [selectedPlan,setSelectedPlan]=useState<any[]>([]);

     //配货单
     const [openPrepare,setOpenPrepare]=useState(false);
     const formRef_prepare=useRef<ProFormInstance>();
     const [printTaskCard,setPrintTaskCard]=useState<{fdata:any[],tdata:any[],source_type?:number}>({fdata:[],tdata:[],source_type:1});
     const [total,setTotal]=useState(0);
      // const [commissionRec,setCommissionRec]=useState<any>({});

     const [selectedLineKeys,setSelectedLineKeys]=useState<any[]>([]);

//当组件选择物料时，更新表格并重载--------------
      useEffect(()=>{
                   if(material.length>0){
                   var x:any[]=editable_refProduce2.current?.getRowsData?.();
                   var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
           
                   // alert(JSON.stringify(x));
                   if(x==undefined)
                      x=[];
                      material.map((item:any)=>{
                      x?.push({rid:Math.random().toFixed(10),id:Math.random().toFixed(10).toString(),
                                material_id:item.id,code:item.code,name:item.name,
                                invstd:item.invstd,invstd2:item.invstd2,munit_name:item.munit_name,  
                                quantity_rate:'1/1', isbelongorder:1,
                                // userdefine_id:'[]',
                                pic:item.pic,
                                quantity_require:quantity_total?quantity_total:0,
                                quantity_stock:item.quantity_stock,
                                quantity_islock:item.quantity_islock,
                                quantity_enable:item.quantity_stock-item.quantity_islock,
                                quantity_diff:(quantity_total?quantity_total:0)
                                              -item.quantity_stock+item.quantity_stock,
                                    

                      });
                   });
     
                  //更新到useState中
                  var temp=produceCard.map((item:any)=>{
                      if(item.card_id==selectedCard)
                          return {...item,material_bom:x};
                      else
                         return item;
                  });
                   setProduceCard(temp);
                   form_refProduce.current?.setFieldValue('editable_produce2',x);
                   action_refProduce2.current?.reloadAndRest?.();
                }
                },[material]);

    interface DataType{
        // rid,id,vouch_code,vouch_date,custom_id,custom_name,dep_name,org_id,
        // code,name,invstd,invstd2,userdefine_id,userdefine_name,munit_name,
        // quantity,quantity_done_rate,quantity_done,deliverdate,state,status,
        pic?:string,
        print_count:number,
        id?:number,did?:number,vouch_code?:string,operate_time?:string,custom_id?:number,
        custom_name?:string,org_name?:string,org_id?:number,code?:string,name?:string,
        invstd?:string,invstd2?:string,userdefine_id?:string,userdefine_name?:string,
        munit_name?:string,quantity?:number,quantity_done_rate?:number,quantity_done?:number,
        quantity_done_ass?:number,quantity_doing?:number,memo?:string,
        begindate?:string,enddate?:string, status?:number,sale_vouch_code?:string,
        //新增项2025-04-20
        craft_route_id?:number,craft_route_name?:string,
        quantity_alloc?:number,quantity_alloc_undo?:number,produce_alloc_time?:string,
        planning_quantity?:number,quantity_undone?:number,commission_vendor?:string,

       
    }
    const columns:ProColumns<DataType>[]=[
        {dataIndex:'pic',title:'图片',width:60,search:false,
            // render:(text)=>{
            //     var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
            //     return <Image src={pic} style={{width:50,height:50}} alt='无' />
            render:(text,record,index,k)=>{
                   var pic="/basis_api/file/get2?filename="+record.code;
                     return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
                },
           },
        // {dataIndex:'id',title:'ID'},{dataIndex:'did',title:'did'},
        {dataIndex:'operate_time',title:'下单日期',valueType:'date',search:false,width:100},
        {dataIndex:'custom_name',title:'店铺',width:100},
        {dataIndex:'sale_vouch_code',title:'申报单号',width:100},
        {dataIndex:'vouch_code',title:'分派单号',width:100,search:false},
        
        {dataIndex:'code',title:'SKU编码',width:100},
        {dataIndex:'name',title:'名称',},
        {dataIndex:'invstd',title:'包装规格',search:false},
        // {dataIndex:'invstd2',title:'型号',search:false},
        {dataIndex:'munit_name',title:'主单位',search:false,width:80},
        {dataIndex:'quantity',title:'数量',search:false,width:80},
        {dataIndex:'produce_alloc_time',title:'配货时间',width:80},
        {dataIndex:'print_count',title:'打印次数',width:80},
        // {dataIndex:'quantity_alloc',title:'已分派数',search:false,width:80},
        // {dataIndex:'quantity_alloc_undo',title:'未分派数',search:false,width:80,
        //   onCell:(record,index)=>{
        //     return {
        //       style:{color:'red'},
        //     }
        //   }
        // },
        // {dataIndex:'quantity_done_rate',title:'完成率',valueType:'progress',width:300,search:false,
        //     renderText(text, record, index, action) {
        //         return (record.quantity_done==undefined?0:record.quantity_done)
        //              /(record.quantity==undefined?1:record.quantity)*100
        //     },
        // },
        // {dataIndex:'quantity_done',title:'完工数量',search:false},
        // {dataIndex:'quantity_undone',title:'未完工数量,',search:false,
        //     onCell:(record,index)=>{
        //       return {
        //         style:{color:'red'}
        //       }
        //     }

        // },
        // {dataIndex:'begindate',title:'计划开工日期',valueType:'date',search:false},
        // {dataIndex:'enddate',title:'计划完工日期',valueType:'date',search:false},
        //  {dataIndex:'craft_route_id',title:'工艺ID'},
        //  {dataIndex:'craft_route_name',title:'工艺名称'},
        // {dataIndex:'status',title:'状态',valueType:'select',width:80,
        //     valueEnum:{1:{text:'未审核'},5:{text:'已审核'},
        //     6:{text:'已弃审'},2:{text:'关闭'},3:{text:'删除'},9:{text:'全部'}}
        // }, 
        // {dataIndex:'memo',hidden:true},
    ];
 
    interface DataType2{
        //  id,org_name,business_name,custom_name,code,name,invstd,userdefine_name,
        //  munit_name,quantity,deliverdate,quantity_doing,quantity_done,quantity2,quantity_plan,
        //  quantity_suit,priority,craft_route,bom_version,status,quantity_stock,
         pic?:string,
         rid?:number,id?:number,code?:string,name?:string,
         invstd?:string,userdefine_name?:string,munit_name?:string,quantity_rate?:string,quantity_islock?:number,
         quantity_require?:number,quantity_stock?:number,quantity_enable?:number,quantity_diff?:number
       }
    
       const columns2:ProColumns<DataType2>[]=[
        {dataIndex:'pic',title:'图片' ,editable:false,width:60,
      //     render:(text)=>{
      //         var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
      //         return <Image src={pic}  
      //                style={{width:50,height:50}} alt='无' />
      //    },
      //  },
            render:(text,record,index,k)=>{
                         var pic="/basis_api/file/get2?filename="+record.code;
                         return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
           }},
           {dataIndex:'rid',title:'rid',editable:false,},
          {dataIndex:'id',hidden:true,editable:false,},
          {dataIndex:'code',title:'子件编码',editable:false,width:'9%'},
          {dataIndex:'name',title:'名称',editable:false,width:'16%'},
          {dataIndex:'invstd',title:'包装规格',editable:false,width:'16%'},
          // {dataIndex:'userdefine',title:'型号',editable:false,},
          {dataIndex:'munit_name',title:'单位',editable:false,},
          {dataIndex:'quantity_rate',title:'换算率',},
          {dataIndex:'quantity_require',title:'需求数',editable:false,valueType:'digit'},
          {dataIndex:'quantity_stock',title:'库存数',editable:false,},
          {dataIndex:'quantity_enable',title:'可用数',editable:false,},
          {dataIndex:'quantity_islock',title:'锁定数',editable:false,},
          {dataIndex:'quantity_diff',title:'欠料数',editable:false,
            render:(text:any)=>text>0?<Tag color="red" style={{width:50}}>{text}</Tag>:<Tag>{text}</Tag>,
          }, 
          {
            title:'操作',            
            fixed:'right',
            valueType:'option',
            width:80,
            editable:false,
            render:(text,record,_,action)=>[
              //  <a key='edit2'
              //     onClick={()=>{
              //         alert(record.rid);
              //        action?.startEditable?.(record.rid);}}
              //  >
              //      编辑
              //  </a>,
               <a  key='del2'
                   onClick={()=>{
                     var x:any[]=[];
                     x=editable_refProduce2.current?.getRowsData?.();
                     //  alert(JSON.stringify(x));
                     var temp=x.filter((item)=>item.rid!=record.rid);
                     var t=produceCard.map((item:any)=>{
                         if(item.card_id==selectedCard)
                               return {...item,material_bom:temp};
                           else
                               return item;
                      }) ;
                      //更新删除后的数据
                     setProduceCard(t); 
                     form_refProduce.current?.setFieldValue('editable_produce2',x.filter((item)=>item.rid!=record.rid));
                   }}
               >
                   删除
               </a>,
            ]
         }
        ];
        
    interface DataTypeQuerySale{
       // pic,mid,did,x_id,org_id,custom_id,
       // saletype_id,vouch_code,status,memo,material_code,material_name,
       // material_id,userdefine_id,userdefine_name,invstd,invstd2,munit_name,
       // custom_name,org_name,operater_name,business_name,
       // quantity,quantity_produce_order,quantity_purchase_order,quantity_commission_order,quantity_order_undo
   rid?:number,    
   pic?:string,mid?:number,did?:number,x_id?:number,org_id?:number,custom_id?:number,
   saletype_id?:number,vouch_code?:string,status?:number,memo?:string,material_code?:string,material_name?:string,
   material_id?:number,userdefine_id?:string,userdefine_name?:string,invstd?:string,invstd2?:string,munit_name?:string,
   custom_name?:string,org_name?:string,operater_name?:string,business_name?:string,
   quantity?:number,quantity_produce_order?:number,quantity_purchase_order?:number,
   quantity_commission_order?:number,quantity_order_undo?:number,quantity_planning?:number,
    };

    const columnsQuerySale:ProColumns<DataTypeQuerySale>[]=[
        {dataIndex:'pic',title:'图片',width:220,editable:false,
          //   render:(text)=>{
          //       var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
          //       return <Image src={pic} style={{width:50,height:50}} alt='无' />
          //       },
          //  },
           render:(text,record,index,k)=>{
                             var pic="/basis_api/file/get2?filename="+record.material_code;
                             return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
               }},
        {dataIndex:'rid',title:'rid',editable:false},
        {dataIndex:'mid',hidden:true,editable:false},
        {dataIndex:'did',title:'DID',editable:false,},
        // {dataIndex:'userdefine_id',title:'自定义ID',editable:false,},
        // {dataIndex:'userdefine_name',title:'自定义值',editable:false,},
        // {dataIndex:'pic',title:'图片',editable:false,},
        {dataIndex:'vouch_code',title:'店铺申报单号',editable:false,},
        {dataIndex:'custom_name',title:'店铺',editable:false,},
        {dataIndex:'org_name',title:'部门',editable:false},{dataIndex:'business_name',title:'业务员',editable:false},
        {dataIndex:'material_code',title:'SKU编码',editable:false},
        {dataIndex:'material_name',title:'名称',editable:false},{dataIndex:'invstd',title:'包装规格',editable:false},
        {dataIndex:'invstd2',title:'型号',editable:false},{dataIndex:'munit_name',title:'单位',editable:false},{dataIndex:'quantity',title:'申报单数量',editable:false},
        {dataIndex:'quantity_produce_order',title:'已下生产数',editable:false},{dataIndex:'quantity_purchase_order',title:'已下采购数',editable:false},
        {dataIndex:'quantity_commission_order',title:'已下分派数',editable:false},
        {dataIndex:'quantity_order_undo',title:'未下单数',editable:false},{dataIndex:'quantity_planning',title:'本次下单数'},
        {dataIndex:'memo',title:'备注',ellipsis:true,editable:false},
        {dataIndex:'status',title:'状态',editable:false,
            render:(text:any)=>status2text(text)}
    ];

    interface DataTypeAdd{
//rid,id,source_type,source_did,source_mid,mid,material_id,userdefine_id,
// userdefine_name,quantity,quantity_planning,
// begindate,enddate,status,memo,state,craft_route_id,bom_id,
// code,name,invstd,invstd2,munit_name,
 pic?:string,
 rid?:number,id?:number,did?:number,source_type?:number,source_did?:number,source_mid?:number,mid?:number,
 material_id?:number,userdefine_id?:string,userdefine_name?:string,quantity_planning?:number,
begindate?:string,enddate?:string,status?:number,memo?:string,state?:number,craft_route_id?:number,bom_id?:number,
material_code?:string,material_name?:string,invstd?:string,invstd2?:string,munit_name?:string,
 // pic,mid,did,x_id,org_id,custom_id,
       // saletype_id,vouch_code,status,memo,material_code,material_name,
       // material_id,userdefine_id,userdefine_name,invstd,invstd2,munit_name,
       // custom_name,org_name,operater_name,business_name,
       // quantity,quantity_produce_order,quantity_purchase_order,quantity_commission_order,quantity_order_undo
    }

const columnsAdd:ProColumns<DataTypeAdd>[]=[
    {dataIndex:'pic',title:'图片',width:220,editable:false,
      //   render:(text:any)=>{
      //       var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
      //       return <Image src={pic} style={{width:50,height:50}} alt='无' />
      //       },
      //  },
       render:(text,record,index,k)=>{
                         var pic="/basis_api/file/get2?filename="+record.material_code;
                         return   <Image src={pic}  style={{width:50,height:50}} alt='无' />
     }},
   {dataIndex:'rid',title:'RID',editable:false},{dataIndex:'id',title:'ID',editable:false},
   {dataIndex:'did',title:'did',editable:false},
   {dataIndex:'source_type',title:'来源类型',editable:false,valueType:'select',
    valueEnum:{1:{text:'店铺申报单'},2:{text:'制单'}}
   },
   {dataIndex:'source_did',title:'来源DID',editable:false},
   {dataIndex:'material_id',title:'物料ID',editable:false},{dataIndex:'material_code',title:'编码',editable:false},
   {dataIndex:'material_name',title:'名称',editable:false},{dataIndex:'invstd',title:'包装规格',editable:false},
   {dataIndex:'invstd2',title:'型号',editable:false},
  //  {dataIndex:'userdefine_id',title:'自定义项ID',editable:false},
  //  {dataIndex:'userdefine_name',title:'自定义项',editable:false},
   {dataIndex:'quantity_planning',title:'下单数量',valueType:'digit',width:120,},
   {dataIndex:'begindate',title:'预计开工日期',valueType:'date',width:160,},
   {dataIndex:'enddate',title:'预计完工日期',valueType:'date',width:160,},
   {dataIndex:'memo',title:'备注',width:'15%'},
  //  {dataIndex:'status',title:'状态',editable:false},
   {
    title:'操作',            
    fixed:'right',
    valueType:'option',
    width:80,
    editable:false,
    render:(text,record,_,action)=>[
      //  <a key='edit2'
      //     onClick={()=>{
      //         alert(record.rid);
      //        action?.startEditable?.(record.rid);}}
      //  >
      //      编辑
      //  </a>,
       <a  key='del2'
           onClick={()=>{
             var x:any[]=[];
             x=editable_ref_add.current?.getRowsData?.();
             //  alert(JSON.stringify(x));
            //  setDataSource(x.filter((item)=>item.id!=record.id));
             // alert(JSON.stringify(x.filter((item)=>item.id!=record.id)));
             // mtable2_ref.current?.reloadAndRest?.();
             formRef_add.current?.setFieldValue('editable_add',x.filter((item)=>item.rid!=record.rid));
           }}
       >
           删除
       </a>,
    ]
 }
];

//新增申报单
    function addFromSaleOrder(){
        setEtype(1);
        setNewOrder([]);
        setOpenSale(true);
    };

    function editFormSaleOrder(){
        if(selectedRecords.length==0)
            message.warning('请先选择要修改的申报单行。');
        else{
            setEtype(0);
            setNewOrder([]);
            setOpenSale(true);
        }
    }
 
    // 查询来源店铺申报单,可编辑数量
    async function querySaleOrder(){
      setSelectedQuery([]);
      var fdata=formRef_query.current?.getFieldsValue();
      fdata={vouch_date:[moment(moment(fdata.vouch_date[0]).toDate()).format('YYYY-MM-DD'),
                         moment(moment(fdata.vouch_date[1]).toDate()).add(1,'day').format('YYYY-MM-DD')],
             custom_id:fdata.custom_id,
             vouch_code:fdata.vouch_code,
             business_id:fdata.business_id,
             material_code:fdata.material_code,
             material_name:fdata.material_name,
             alloc_type:1,
      };
    //   alert(JSON.stringify(fdata));
      const x=await s_getcommontableinfo({x_id:1,source:'v_sale_order_all',cate_id:[],id:0,fdata});
    //   setTdata(x.data[0]);
    //   alert(JSON.stringify(x.data[0]));
      formRef_query.current?.setFieldValue('editable_query',x.data[0]);
    }

    //编辑来源申报单的数量
    function editQuery(){
        const temp=formRef_query.current?.getFieldValue('editable_query');
        // alert(JSON.stringify(temp));
        temp.map((item:any)=>{
            action_ref_query.current?.startEditable(item.rid);
        });
    };

    //保存编辑数据
     function editQuerySave(){
         var temp=formRef_query.current?.getFieldValue('editable_query');
        temp.map((item:any)=>{
            action_ref_query.current?.saveEditable(item.rid);
        });
        // alert(JSON.stringify(temp[0]));
        var st=[];
        st=selectedQuery.map((item:any)=>{
            var t2=temp.filter((item2:any)=>item2.rid==item.rid);
            // alert('---'+JSON.stringify(t2));
            if (t2&&t2.length>0)
               return {...item,quantity_planning:t2[0].quantity_planning};
            else 
               return {...item};
        });
        // alert(JSON.stringify(st));
        setSelectedQuery(st);
     };

    //将来源店铺申报单的行，加入申报单--申报单表应设置一个数据源
    function addQueryToOrder(){
        if(selectedQuery&&selectedQuery.length>0){
              var x:any[]=[];
            // alert(JSON.stringify(selectedQuery));
            x=selectedQuery.map((item:any)=>({...item,source_mid:item.mid,source_did:item.did,source_type:1,
                                                begindate:moment(),enddate:moment().add(1,'day')   ,
                                              }));
            // alert(JSON.stringify(x));
            formRef_add.current?.setFieldValue('editable_add',newOrder.concat(x));
            setNewOrder(newOrder.concat(x)); 
          }
        else
            message.warning('请选选择要加入的行');
    };
    
    //编辑申报单
    function editOrder(){
       var t=formRef_add.current?.getFieldValue('editable_add');
       t.map((item:any)=>{
          action_ref_add.current?.startEditable(item.rid);
       });
    }

    //保存申报单
    async function saveOrder(){
        //先完成编辑
        // alert(111);
        const t=formRef_add.current?.getFieldValue('editable_add');
        // alert(JSON.stringify(t));
        t.map((item:any)=>action_ref_add.current?.saveEditable(item.rid));
       

        var fdata=formRef_add.current?.getFieldsValue();
        fdata={...fdata,
                 alloc_type:1,
                operate_time:moment().format('YYYY-MM-DD'),   
                editable_add:fdata.editable_add.map((item:any)=>({
                material_id:item.material_id,
                userdefine_id:item.userdefine_id?JSON.parse(item.userdefine_id):null,
                userdefine_name:item.userdefine_name,
                source_mid:item.source_mid,
                source_did:item.source_did,
                source_type:item.source_type,
                quantity:item.quantity_planning,
                begindate:moment(moment(item.begindate).toDate()).format('YYYY-MM-DD'),
                enddate:moment(moment(item.enddate).toDate()).format('YYYY-MM-DD'),
                memo:item.memo,
                did:item.did,
            }))
        };
        // alert(JSON.stringify(fdata));
        // source,x_id,operater_id,etype,fdata
        const x=await s_updateInfo({source:'produce_order',x_id:1,operater_id:1,etype,fdata});
        if(x.success){
            actionRef_main.current?.reloadAndRest?.();
            message.success('保存成功');
        }else
            message.error('保存失败');
    }

    //编辑主表申报单
    function editOrderMain(){
      
    //   alert(JSON.stringify(fdata));

    if(selectedRecords&&selectedRecords.length>0){
        // message.success('开始编辑');
        var id=selectedRecords?selectedRecords[0].id:0;
        var fdata=formRef_main.current?.getFieldValue('table_main').filter((item:any)=>item.id==id);
        fdata=fdata.map((item:any)=>{
          return {...item,
              rid:Math.random().toFixed(10),
              quantity_planning:item.quantity, 
              }
        });
        
        //   alert(JSON.stringify(fdata));
        var tr={};
        tr={
                 vouch_code:selectedRecords?selectedRecords[0].vouch_code:null,
                 opearte_time:selectedRecords?selectedRecords[0].operate_time:null,
                 org_id:selectedRecords?selectedRecords[0].org_id:null,
                 status:selectedRecords?selectedRecords[0].status:null,
                 memo:selectedRecords?selectedRecords[0].memo:null,
                 id:selectedRecords?selectedRecords[0].id:null,
                 editable_add:fdata,
              };
          setSelectedOrder(tr);    
          setNewOrder(fdata);
          setEtype(0);
          setOpenSale(true);
    }else
      message.warning('请选择要编辑的申报单');
    };

    function exitOrder(){
        setSelectedOrder({});
        setProduceCard([]);
        setOpenQuery(false);
    };

    //  操作询价单/关闭/删除/恢复
       async function operateInfo(n:number){
        // source,x_id,operater_id,otype,id
        if(selectedRecords.length==0)
           message.warning('请选择要操作的行');
        else{
         const x=await s_operateInfo({x_id:1,source:'produce_order_main',
            operater_id:1,otype:n,id:selectedRecords[0].id});
         if(x.success){
           message.success('操作成功');
           actionRef_main.current?.reloadAndRest?.();
         }else
           message.error('操作错误，请联系管理员。');
        }
     }

     //参数：3分派--------------------------------------------------
           async function forProduce(etype:number){
              var t=produceCard.filter((item:any)=>!item.material_bom||item.material_bom.length==0); 
             if(form_refProduce.current?.getFieldValue('vouch_code')==undefined) // if 1
                  message.warning('请填写申报单号');
             else if(t.length>0)
                  message.warning('请先设置工序及物料明细');
             else{    
               const vouch_code=form_refProduce.current?.getFieldValue('vouch_code');
               const operate_time=form_refProduce.current?.getFieldValue('operate_time');
               const org_id=form_refProduce.current?.getFieldValue('org_id');
               const memo=form_refProduce.current?.getFieldValue('memo');
               const status=form_refProduce.current?.getFieldValue('status');
               // const begindate=form_refProduce.current?.getFieldValue('begindate');
               // const enddate=form_refProduce.current?.getFieldValue('enddate');
               // const craft_route_id=selectedPlanRecord[0].craft_route_id;
               // const source_mid=selectedPlanRecord[0].source_mid;
               // const source_did=selectedPlanRecord[0].source_did;
               // alert(JSON.stringify(produceCard));
               var card=produceCard.map((item:any)=>{
                   return { 
                     begindate:moment(moment(item.begindate).toDate()).format('YYYY-MM-DD'),
                     enddate:moment(moment(item.enddate).toDate()).format('YYYY-MM-DD'),
                     card_id:item.card_id,
                     // card_name:item.card_name,
                     workcenter_id:item.default_workcenter_id,
                     workgroup_id:item.default_workgroup_id,
                     quantity_total:item.quantity_total,
                     quantity:item.quantity_unit,
                     quantity_pc:item.quantity_pc,
                     material_bom:item.material_bom.map((item2:any)=>({
                          material_id:item2.material_id,   
                          userdefine_id:item2.userdefine_id?JSON.parse(item2.userdefine_id):null,
                          userdefine_name:item2.userdefine_name,
                          quantity_rate:item2.quantity_rate,
                          quantity:item2.quantity_require,
                          })),
                   };
               });
               
               var pitem=selectedPlanRecord[0];
               var plan={
                    craft_route_id:pitem.craft_route_id,
                    sourcetype_id:pitem.planning_type,
                    source_mid:pitem.source_mid,
                    source_did:pitem.source_did,
                    produce_did:pitem.did,
                    material_id:pitem.material_id,
                    userdefine_id:pitem.userdefine_id?JSON.parse(pitem.userdefine_id):null,
                    userdefine_name:pitem.userdefine_name,
                    quantity:pitem.planning_quantity,
                    planning_begindate:moment(moment(pitem.planning_begindate).toDate()).format('YYYY-MM-DD'),
                    planning_enddate:moment(moment(pitem.planning_enddate).toDate()).format('YYYY-MM-DD'),
                    quantity_suit:pitem.quantity_suit,
                    begindate:moment(moment(pitem.begindate).toDate()).format('YYYY-MM-DD'),
                    enddate:moment(moment(pitem.enddate).toDate()).format('YYYY-MM-DD'),
                   };
     
               // alert(JSON.stringify(plan));
               //  alert(JSON.stringify(card));
               // alert(JSON.stringify(produceCard));
             //   alert(JSON.stringify({x_id:1,operater_id:1,vtype:1,
             //     tdata:{vouch_code,org_id,memo,status,
             //           mdata:plan,
             //           fdata:card}
             //  }));

              //  const x=await s_createProduceAlloc({x_id:1,operater_id:1,vtype:etype,
              //     tdata:{vouch_code,org_id,memo,status,
              //           mdata:plan,
              //           fdata:card}
              //  });
            //    if(x.success){
            //           message.success('下达成功！');
            //           actionRef_main.current?.reload?.();
            //          //  alert(JSON.stringify(produceCard));
            //          //  setProduceCard([]);
            //      }
            //    else
            //      message.error('下达失败，请检查');
            //  };// end if 1
            alert(JSON.stringify(produceCard));
                  }
           };
     
           //进入申报单主界面----------------------------------------------------------------
           function beginProduce(){
             if(selectedPlanRecord&&selectedPlanRecord.length!=1)
                message.warning('请选择、并仅选择一行需求。');
             else if(selectedPlanRecord[0].planning_type!=1)
               message.warning('请选择“计划类型：生产”的一行需求');
             else{
               //  setProduceCard([]);
                setOpenProduce(true);
             }
           };

           //单击工序时，调出对应的物料明细，供修改
           function getCardBom(taskcard_mid:number,card_id:number){
              // alert(card_id);
            const x:any=produceCard.filter((item:any)=>item.id==taskcard_mid);   
            setSelectedCard(card_id);
            // alert(JSON.stringify(produceCard));
            var y=x&&x.length>0&&x[0].material_bom?x[0].material_bom:[];
            // alert(JSON.stringify(y));
            // form_refProduce.current?.setFieldValue('editable_produce2',y);
            // alert(JSON.stringify(x));
             form_refProduce.current?.setFieldsValue({
                     card_id:x[0].card_id,
                     default_workcenter_id:x[0].default_workcenter_id,
                     default_workgroup_id:x[0].default_workgroup_id,
                     begindate:x[0].begindate?x[0].begindate:moment(),
                     enddate:x[0].enddate?x[0].enddate:moment(),
                     quantity_total:x[0].quantity_total?x[0].quantity_total:0,
                     quantity_unit:x[0].quantity_unit,
                     quantity_pc:x[0].quantity_pc,
                     editable_produce2:y, 
                     //2025-06-08新增类型
                     dotype:x[0].dotype,
             });
           };

            // 根据选择的工序卡片，设置卡片信息和物料信息
            async function getCardDetail(card:any){
                   //读取对应的子件明细，并赋给明细表
                   // x_id,cate_id,id,source,fdata
                   //当为空时，则调用产品工艺路线下BOM明细
                   // alert(JSON.stringify(card));
                   // alert(JSON.stringify(card.material_bom));
                   var standard_bom:any[]=[];
                   // alert(JSON.stringify(card));
                   if(!card.material_bom){
                   const x=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,
                                                        source:'v_material_craft_route_card_bom3',
                                                        fdata:{
                                                           material_id:selectedPlanRecord&&selectedPlanRecord.length>0?selectedPlanRecord[0].material_id:0,
                                                           craft_route_id:selectedPlanRecord&&selectedPlanRecord.length>0?selectedPlanRecord[0].craft_route_id:0,
                                                           card_id:card.card_id,
                                                        }});
                     standard_bom=x.data[0].map((item:any)=>{
                   // 计算需求总数和差异
                     var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
                         quantity_total=quantity_total?quantity_total:0;
                     var n1=item.quantity_rate.substring(0,item.quantity_rate.indexOf('/'));
                     var n2=item.quantity_rate.substring(item.quantity_rate.indexOf('/')+1);
                      return {...item,
                          quantity_require:quantity_total*n2/n1,
                          quantity_diff:quantity_total*n2/n1-item.quantity_stock+item.quantity_islock,
                       };
                     });
                   //  alert(JSON.stringify(standard_bom));
                   
                  };//end if
                   // alert(card.card_id);
                   setSelectedCard(card.card_id);
                   //更新produceCard----保存界面中的所有信息
                   // var quantity_total=form_refProduce.current?.getFieldValue('quantity_total');
                   // var quantity_unit=form_refProduce.current?.getFieldValue('quantity_unit');
                   // var quantity_pc=form_refProduce.current?.getFieldValue('quantity_pc'); 
                   var p=produceCard.map((item:any)=>{
                       if(item.card_id==card.card_id)
                         return {...item,
                           material_bom:standard_bom.length==0?item.material_bom:standard_bom,
                           quantity_total:card.quantity_total?card.quantity_total:0,
                           quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
                           quantity_pc:card.quantity_pc?card.quantity_pc:1,  
                          };
                     else
                        return {...item,
                         // quantity_total:card.quantity_total?card.quantity_total:0,
                         // quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
                         // quantity_pc:card.quantity_pc?card.quantity_pc:1, 
                       };
                    });
                    setProduceCard(p);
                   //  alert(JSON.stringify(p.filter(item=>item.card_id==card.card_id)));
                    //更新界面表格
                   form_refProduce.current?.setFieldsValue({
                     card_id:card.card_id,
                     default_workcenter_id:card.default_workcenter_id,
                     default_workgroup_id:card.default_workgroup_id,
                     
                     begindate:card.begindate?card.begindate:moment(),
                     enddate:card.enddate?card.enddate:moment(),
                     quantity_total:card.quantity_total?card.quantity_total:0,
                     quantity_unit:card.quantity_unit?card.quantity_unit:card.quantity_total?card.quantity_total:0,
                     quantity_pc:card.quantity_pc?card.quantity_pc:1,
                     editable_produce2:card.material_bom?card.material_bom:standard_bom, 
                     //2025-06-08新增类型
                     dotype:card.dotype,
                   });
                 }
           
                 //调整子件换算率
                 function adjustQuantityRate(){
                     const x=form_refProduce.current?.getFieldValue('editable_produce2');
                     x.map((item:any)=>{
                        action_refProduce2.current?.startEditable(item.rid);
                     });
                 }
           
                 //保存子件换算率
                 function saveQuantityRate(){
                       const x=form_refProduce.current?.getFieldValue('editable_produce2');
                       var t2=x.map((item:any)=>{
                           action_refProduce2.current?.saveEditable(item.rid);
                           var v=form_refProduce.current?.getFieldValue('quantity_total');
                           var n1=item.quantity_rate.substring(0,item.quantity_rate.indexOf('/'));
                           var n2=item.quantity_rate.substring(item.quantity_rate.indexOf('/')+1);
                           n1=n1.length==0?1:n1;
                           n2=n2.length==0?1:n2;
                           item.quantity_require=(v?v:0)*n2/n1;
                           item.quantity_diff=(v?v:0)*n2/n1-item.quantity_stock+item.quantity_islock;
           
                           return item;
                     });
                     //更新卡片物料明细
                     var t=produceCard.map((item:any)=>{
                         if(item.card_id==selectedCard)
                             return {...item,material_bom:t2};
                         else
                             return item;
                     });
                     setProduceCard(t);
                 }

                 
      //进入申报单主界面----------------------------------------------------------------
      async function beginAlloc(){
        if(selectedPlanRecord&&selectedPlanRecord.length!=1)
           message.warning('请选择、并仅选择一行需求。');
        // else if(selectedRecords[0].planning_type!=1)
        //   message.warning('请选择“计划类型：生产”的一行需求');
        else{
          //  setProduceCard([]);
          //1，分派时，自动生成工序、用料明细数据。

          //2， 在点击立即分派时，只可以修改工作中心/工作组/分派类型，及增减明细用料。不允许修改派工批量。
          //未来需要修改批量时，另行手工分派。
          var did=selectedPlan[0];
          const x=await s_getProduceInfo({source:'v_produce_do_taskcard_alloc',x_id:1,
                                  fdata:{id:did}});
          var y:any[]=[];
          var card_info=x.data[0];
          var card_bom=x.data[1];
          
          card_info.map((item:any)=>{
              var obj:any={};
              obj.id=item.id;
              obj.card_id=item.card_id;
              obj.card_name=item.card_name;
              obj.quantity_total=item.quantity_total;
              obj.quantity_unit=item.quantity_unit;
              obj.quantity_pc=item.quantity_pc;
              obj.default_workcenter_id=item.default_workcenter_id;
              obj.default_workgroup_id=item.default_workgroup_id;
              obj.begindate=item.begindate;
              obj.enddate=item.enddate;
              obj.dotype=item.dotype;
              obj.source_produce_order_did=item.source_produce_order_did;
              //获取card物料明细
              var bom:any[]=[];
              var card_bom2=card_bom.filter((item3:any)=>item3.taskcard_mid==item.id);
              // alert(JSON.stringify(card_bom));

              if(card_bom2&&card_bom2.length>0)
               card_bom2.map((item2:any)=>{
                 var obj_bom:any={};
                 obj_bom.material_id=item2.material_id;
                 obj_bom.code=item2.code;
                 obj_bom.name=item2.name;
                 obj_bom.invstd=item2.invstd;
                 obj_bom.pic=item2.pic;
                 obj_bom.quantity=item2.quantity;
                 obj_bom.quantity_require=item2.quantity_require;
                 obj_bom.quantity_stock=item2.quantity_stock;
                 obj_bom.quantity_enable=item2.quantity_enabl;
                 obj_bom.quantity_diff=item2.quantity_diff;
                 obj_bom.quantity_islock=item2.quantity_islock;
                 obj_bom.munit_name=item2.munit_name;
                 obj_bom.quantity_rate=item2.quantity_rate;
                 //加入到物料明细数组
                 bom.push(obj_bom);
              });
              //加入卡片物料明细属性
              obj.material_bom=bom;
              y.push(obj);
          });

           setProduceCard(y);
           setOpenProduce(true);
          //  alert(JSON.stringify(y));
        };
      };

      //打开配货单
     async function doPrepareMaterial(){
        //根据当前选中行的did，获取选中的信息
        if(selectedPlanRecord.length==0)
           message.warning('请选择要配货的物料');
        else{
           var produce_did=selectedPlanRecord[0].did;
          //  x_id,cate_id,id,source,fdata
           const x=await s_getcommontableinfo({x_id:1,cate_id:[],id:produce_did,source:'print_taskcard_material1'});
          //  alert(JSON.stringify(x.data[0]));
           if(x.data[0].length>0)
             setPrintTaskCard({fdata:x.data[0],tdata:x.data[1],source_type:1});
          //  if(x.data[2].length>0)
            //  setCommissionRec(x.data[2][0]); 
           setOpenPrepare(true);
        }
     };

     //退出配货单打印
     function closePrepare(){
        setPrintTaskCard({fdata:[],tdata:[],source_type:1});
        // setCommissionRec({});
        // alert(111);
        setOpenPrepare(false);
     };

     //打印申报单。
    async function printPrepare(){
        // alert('开始打印');
        if(formRef_prepare.current?.getFieldValue('is_tostock')==undefined)
            message.warning('打印失败！请先下发配货单');
        else{  
            printJS({
                      printable:'print',
                      type:'html',
                      targetStyles:['*'],
                      // header:'华磊工贸',
                      style:`{@page{size:'auto';}  h2{font-size:50}}`,
                      maxWidth:1200,
                      onLoadingStart:()=>{
                        console.log('开始打印');
                      },
                      onLoadingEnd:()=>{
                        console.log('结束打印');
                      }
                    });

               //  记录打印次数------------------------------------------------
                          // alert(JSON.stringify(selectedPlanRecord[0].did));
                         const  x=await s_produce_updateInfo({x_id:1,source:'print_taskcard',
                                     etype:1,operater_id:1,
                                     fdata:{id:selectedPlanRecord.length>0?selectedPlanRecord[0].did:0}
                                 });
                        // alert('2222'); 
                        //  if(x.success){
                        //     message.success('打印成功');
                            // alert('9999');
                            actionRef_main.current?.reloadAndRest?.();
                            // alert('66668888');
                        //  }
                        //  else
                        //     message.error('打印失败');      
                  };
    };

    //下发配货单，自动生成未审核的材料出库单
    async function stockPrepare(){
        // alert(JSON.stringify(printTaskCard));
        if(!printTaskCard||printTaskCard.fdata.length==0)
               message.warning('申报单还没有分派，不能下发。');
         else{ 
           //简化参数后，再传递
           var f=printTaskCard.fdata.map((item:any)=>({
              source_produce_order_did:item.source_produce_order_did,
              taskcard_id:item.taskcard_id,
              x_id:item.x_id,
              taskcard_sno:item.taskcard_sno,
              produce_vouch_code:item.produce_vouch_code,
              org_id:item.org_id,
              
           }));
           var t=printTaskCard.tdata.map((item:any)=>({
              source_produce_order_did:item.source_produce_order_did,
              taskcard_mid:item.taskcard_mid,
              quantity:item.quantity,
              material_id:item.material_id,
           }));
           const x=await s_stockOut({x_id:1,opertater_id:1,etype:1,
                   source:'stock_out_produce_taskcard',tdata:{fdata:f,tdata:t,source_type:1,alloc_type:1}});
           if(x.success){
                formRef_prepare.current?.setFieldValue('is_tostock',1);
                message.success('配货申请下发成功');
              }
            else
                message.error('配货申请下发侧选，请联系管理员') ;
         };
    };

    //立即分派：只更新卡片的内容，不更新卡片的物料明细。作为采购分配工序到委外/自制的源头。2025-06-08  44.1
    async function allocProduce(){
        var tdata=produceCard.map((item:any)=>{
          return {
            id:item.id,
            workcenter_id:item.default_workcenter_id,
            workgroup_id:item.default_workgroup_id,
            begindate:item.begindate?moment(moment(item.begindate).toDate()).format('YYYY-MM-DD'):moment().format('YYYY-MM-DD'),
            enddate:item.enddate?moment(moment(item.enddate).toDate()).format('YYYY-MM-DD'):moment().format('YYYY-MM-DD'),
            dotype:item.dotype,
            // status:item.status,  //后续再调整，即在派工时可以停用工序。
          };
        });
        // alert(JSON.stringify(tdata));
        // source,x_id,operater_id,etype,fdata
        const x=await s_purchase_updateInfo({source:'alloc_produce_taskcard',x_id:1,operater_id:1,
                          etype,fdata:tdata});
        if(x.success){
           message.success('分派成功');
           setProduceCard([]);
           actionRef_main.current?.reloadAndRest?.();
           }
        else
           message.error('分派失败，请联系管理员。');
    };

    //指派外加工商-------------------2025-06-09-----
    async function allocVendor(did:number){
         const vendor=formRef_prepare.current?.getFieldFormatValue?.('vendor');
         const price=formRef_prepare.current?.getFieldFormatValue?.('price');
         var wfdate=formRef_prepare.current?.getFieldFormatValue?.('wfdate');
         const memo=formRef_prepare.current?.getFieldFormatValue?.('memo');

         if(price==undefined||vendor==undefined||wfdate==undefined)
            message.warning('错误！内部备料商、单价、内部备料日期不能为空，请检查');
          else{
             wfdate=moment(moment(wfdate).toDate()).format('YYYY-MM-DD');
             const x=await s_purchase_updateInfo({source:'allocCommission',x_id:1,operater_id:1,
                          fdata:{did,vendor,price,wfdate,memo}});

            // alert(JSON.stringify({did,commission_name,price,wfdate,memo}));
             if(x.success)
                  message.success('内部备料成功');
             else
                  message.error('内部备料失败，请联系管理员');
          }
    };

    // =====================================================================================================
    return <>
       <ProCard title='申报单管理' style={{height:'80vh'}}
         extra={<Space>
            {/* <Button onClick={()=>addFromSaleOrder()}>从店铺申报单新增</Button> */}
            {/* <Button>手工新增</Button> */}
            {/* <Button onClick={()=>editOrderMain()}>编辑申报单</Button>
            <Button onClick={()=>operateInfo(5)}>审核</Button>
            <Button onClick={()=>operateInfo(6)}>取消审核</Button> */}
            {/* <Button onClick={()=>beginAlloc()} style={{width:120}}>开始分派</Button> */}
            <Button onClick={()=>doPrepareMaterial()}>生成配货单</Button>
            {/* <Button onClick={()=>operateInfo(2)}>关闭</Button>
            <Button onClick={()=>operateInfo(3)}>删除</Button>
            <Button onClick={()=>operateInfo(1)}>恢复</Button> */}
         </Space>}
       >
        <ProForm formRef={formRef_main} submitter={false} layout="horizontal">
         <EditableProTable<DataType>
             actionRef={actionRef_main}
             editableFormRef={editableRef_main}
             name='table_main'
             search={{span:4}}
             options={false}
             rowKey='did'
             columns={columns}
            //  dataSource={tdata}
            // request={async ()=>{
            //     // x_id,cate_id,id,source,fdata
            //     const x=await s_getcommontableinfo({x_id:1,cate_id:[],id:0,source:'v_produce_order_detail',fdata:{alloc_type:1}});
            //     // alert(JSON.stringify(x.data));
            //     return {
            //         data:x.data[0],
            //         success:true,
            //     }
            // }}
           request={async (param)=>{
                    const x=await s_getProduceInfo({source:'v_produce_order_detail1',x_id:1,
                                  fdata:{id:0,param,alloc_type:1,dotype:1}});
                     setTotal(x.data[0][0].count);
                      return{
                            data:x.data[1],
                            success:true,
                          }
                       }}

            rowSelection={{
                type:'radio',
                selectedRowKeys:selectedLineKeys,
                async onChange(selectedRowKeys:any, selectedRows:any, info) {
                      //  var did:any[]=[];
                      //  selectedRows.map((item:any)=>{
                      //      did.push({did:item.did,quantity_plan:item.quantity_plan,quantity_suit:item.quantity_suit});
                      //  });
                       setSelectedRecords(selectedRows);
                       setSelectedPlan(selectedRowKeys);
                       setSelectedPlanRecord(selectedRows);
                       setSelectedLineKeys(selectedRowKeys);
                       //调取工序卡片，生成下单界面的工序列表
                      //  x_id,cate_id,id,source,fdata
                      //  const x=await s_getcommontableinfo({x_id:1,cate_id:[],
                      //                  id:selectedRows&&selectedRows.length>0?selectedRows[0].material_id:0,
                      //                  source:'v_material_craft_route_card',fdata:{}});
                      //   // alert(JSON.stringify(x.data[0]));
                      //  var a:any[]=[];
                      //  x.data[0].map((item:any)=>{
                      //    a.push({card_id:item.card_id,
                      //            card_name:item.card_name,
                      //            default_workcenter_id:item.default_workcenter_id,
                      //            default_workgroup_id:item.default_workgroup_id,
                      //            quantity_total:selectedRows&&selectedRows.length>0
                      //                  ?selectedRows[0].quantity_alloc_undo:0,
                      //           quantity_unit:selectedRows&&selectedRows.length>0
                      //                  ?selectedRows[0].quantity_alloc_undo:0,
                      //           quantity_pc:1,
                      //           dotype:item.dotype,
                      //           //  material_bom:[],
                      //           });
                      //  });
                      // //  alert(JSON.stringify(a));
                      //  setProduceCard(a);
                    },
               
            }}
            onRow={(record)=>{
            return {
              onClick:()=>{
                const k=record.did;
                // if(selectedKeys.includes(k) )
                //      setSelectedKeys(selectedKeys.filter(item=>item.id!=k));
                // else
                     setSelectedRecords([record]);
                     setSelectedPlan([k]);
                     setSelectedPlanRecord([record]);
                     setSelectedLineKeys([k]);
              },
            }
           }}
            recordCreatorProps={false}
             scroll={{y:'50vh'}}
                    pagination={{
                    showQuickJumper:true,
                    showSizeChanger:true,
                    defaultPageSize:10,
                    defaultCurrent:1,
                    total,
                  }}
         />
         </ProForm>
       </ProCard>

       {/* 从店铺申报单新增------------------------------------------------------------------ */}
       <Modal open={openSale} width='95%' destroyOnClose closable onCancel={()=>setOpenSale(false)} 
          onClose={()=>setOpenSale(false)}
            okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} style={{top:10}}>
           <ProCard title='从店铺申报单新增' style={{height:900,overflow:'auto'}}
                 extra={<Space>
                    <Button onClick={()=>setOpenQuery(true)}>选择店铺申报单</Button>
                    <Button onClick={()=>editOrder()}>编辑申报单</Button>
                    <Button onClick={()=>formRef_add.current?.submit()}>保存申报单</Button>
                    <Button onClick={()=>setOpenSale(false)}>退出申报单</Button>
                 </Space>}
             >
                {/* 店铺申报单查询：查询条件和临时结果--------------------------------- */}
                <Drawer open={openQuery} placement="top" destroyOnClose onClose={()=>setOpenQuery(false)} 
                       style={{height:'90vh'}}
                    >
                   <ProCard title='从店铺申报单生成'   style={{height:'78vh'}} 
                      extra={<Space>
                        <Button onClick={()=>querySaleOrder()}>开始查询</Button>
                        <Button onClick={()=>editQuery()}>编辑数量</Button>
                        <Button onClick={()=>editQuerySave()}>保存数量</Button>
                        <Button onClick={()=>addQueryToOrder()}>加入申报单</Button>
                        <Button onClick={()=>exitOrder()}>退出</Button>
                      </Space>}>
                       <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:4}}
                           initialValues={{vouch_date:[moment().add(-7,'day').format('YYYY-MM-DD'),moment().format('YYYY-MM-DD')]}}
                           formRef={formRef_query}
                          >
                            <Row gutter={8}>
                                <Col span={8}>
                                   <ProFormDateRangePicker name='vouch_date' label='申报单日期' width={300}/>
                                   <ProFormText name='vouch_code' label='申报单编号' width={300}/>
                                </Col>
                                <Col span={8}>
                                    <ProFormSelect name='custom_id' label='店铺' width={300}
                                       showSearch
                                       request={async ()=>{
                                              const x=await s_getSelectData({x_id:1,source:'v_custom'});
                                              return x.data;
                                            }}
                                    />
                                    <ProFormSelect name='business_id' label='业务员' width={300}
                                       showSearch
                                       request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'v_businesser'});
                                           return x.data;
                                         }}
                                    /> 
                                </Col>
                                <Col span={8}>
                                    <ProFormText name='material_code' label='物料编码' width={300}/>
                                   <ProFormText name='material_name' label='物料名称' width={300}/>
                                </Col>
                            </Row>
                         <EditableProTable<DataTypeQuerySale>
                               name='editable_query'
                               actionRef={action_ref_query}
                               editableFormRef={editable_ref_query}
                               columns={columnsQuerySale} 
                               rowKey='rid'
                               search={false}
                               options={false}
                               editable={{
                                type:'multiple'
                               }}
                               recordCreatorProps={false}
                               rowSelection={{
                                type:'checkbox',
                                onChange(selectedRowKeys, selectedRows:any, info) {
                                    setSelectedQuery(selectedRows);
                                },
                               }}
                               scroll={{y:'65vh'}}
                            />   
                       </ProForm>
                       
                   </ProCard>
                </Drawer>
{/* 申报单主界面--------------------------------------------------------------------------------------- */}
                <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:5}}
                    formRef={formRef_add}
                    onFinish={()=>saveOrder()}
                    initialValues={etype==1?{
                            operate_time:moment(),status:1,
                             }
                          :{
                             ...selectedOrder,
                          }}
                >
                    <ProFormText name='id' hidden={true}/>
                    <Row gutter={8}>
                       <Col span={8}>
                           <ProFormText name='vouch_code' label='申报单号' width={200}
                            //  rules={[{required:true,message:'必填项'}]}
                           />
                           <ProFormSelect name='org_id' label='部门' width={200}
                                showSearch
                                       request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'base_organization'});
                                           return x.data;
                                         }}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormDatePicker name='operate_time' label='下单日期' width={200}/>
                           <ProFormRadio.Group name='status' label='状态' width={200} 
                               options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormTextArea name='memo' label='备注' width={300}/>
                       </Col>
                    </Row>
                   <EditableProTable<DataTypeAdd>
                      rowKey='rid'
                      name='editable_add'
                      search={false}
                      options={false}
                      columns={columnsAdd}
                      recordCreatorProps={false}
                      editable={{
                        type:'multiple'
                      }}
                      actionRef={action_ref_add}
                      editableFormRef={editable_ref_add}
                   />
                </ProForm>

           </ProCard>
      </Modal>

      {/* 生产分派--------------------------------------------------------------------------------- */}
      <Modal title='生产分派明细' open={openProduce} width={'96%'} closable destroyOnClose 
                  onCancel={()=>setOpenProduce(false)}  
                  onClose={()=>setOpenProduce(false)} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} 
                  style={{top:20}}
                >
                <ProCard style={{height:'85vh'}}
                   extra={<Space>
                        {/* <Button  onClick={()=>forProduce(1)}>下达生产</Button> */}
                        <Button  onClick={()=>allocProduce()}>立即分派</Button>
                        
                   </Space>}
                >
                 <ProForm formRef={form_refProduce} submitter={false}
                     layout="horizontal" labelAlign="left" labelCol={{span:6,offset:0}}
                     initialValues={{
                         editable_produce:selectedPlanRecord.length>0?selectedPlanRecord:null,
                         quantity_total:selectedPlanRecord.length>0?selectedPlanRecord[0]?.quantity_alloc_undo:null,
                         operate_time:moment(),status:1,
                         vouch_code:selectedPlanRecord.length>0?selectedPlanRecord[0]?.vouch_code:null,
                         org_id:selectedPlanRecord.length>0?selectedPlanRecord[0]?.org_id:null,
                         quantity_unit:selectedPlanRecord.length>0?selectedPlanRecord[0]?.quantity_alloc_undo:null,
                         quantity_pc:1,
                    }}
                 >
                  <Row gutter={8}>
                       <Col span={8}>
                           <ProFormText name='vouch_code' label='申报单号' width={200}
                             rules={[{required:true,message:'必填项'}]}
                           />
                           <ProFormSelect name='org_id' label='部门' width={200}
                                showSearch
                                       request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'base_organization'});
                                           return x.data;
                                         }}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormDatePicker name='operate_time' label='下单日期' width={200}/>
                           <ProFormRadio.Group name='status' label='状态' width={200} 
                           rules={[{required:true,message:'必填项'}]}
                               options={[{value:1,label:'正常'},{value:2,label:'关闭'},{value:3,label:'删除'}]}
                           />
                       </Col>
                       <Col span={8}>
                           <ProFormTextArea name='memo' label='备注' width={300}/>
                       </Col>
                    </Row>
                 <Splitter style={{ height: '100%', }} layout="vertical">
                      <Splitter.Panel defaultSize="30%" min="20%" max="70%" >
                        <ProCard  style={{height:'18vh',overflow:'auto'}}>
                          {/* {JSON.stringify(produceCard)} */}
                        <EditableProTable<DataType>
                              name='editable_produce'
                              editableFormRef={editable_refProduce}
                              rowKey='rid'
                              search={false}
                              options={false}
                              columns={columns}
                               dataSource={[]}
                              // rowSelection={{
                              //     type:'checkbox',
                              // }}
                              recordCreatorProps={false}
                              actionRef={action_refProduce}
                              scroll={{y:'10vh'}}
                         />
                        </ProCard>
                      </Splitter.Panel>
                     <Splitter.Panel>
                        <Splitter style={{height:'100%'}}>
                            <Splitter.Panel defaultSize='10%'>
                              <ProCard title='生产工序'>
                              <List >
                                {/* <List.Item style={{width:100,marginLeft:50,fontWeight:'bold'}}>工艺流程</List.Item>
                                <List.Item style={{width:100,color:'red',marginLeft:50}}> 穿钩</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>贴牌</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>装袋</List.Item>
                                <List.Item style={{width:100,color:'blue',marginLeft:50}}>装箱</List.Item> */}
                                {
                                  produceCard.map((item:any)=><List.Item 
                                        style={{width:100,
                                                 marginLeft:60,
                                                color:selectedCard==item.card_id?'red':'blue'}}
                                                               onClick={()=>getCardBom(item.id,item.card_id)}>
                                                              {item.card_name}</List.Item>)
                                }
                                </List>
                              </ProCard>
                            </Splitter.Panel>
                            <Splitter.Panel defaultSize='22%'>
                            <List>
                                <List.Item style={{width:100,marginLeft:50,fontWeight:'bold'}}>工艺任务</List.Item>
                              </List>
                              {/* <ProForm submitter={false} layout="horizontal" labelAlign="left" labelCol={{offset:0,span:7}}
                                 style={{marginLeft:20}}  
                              > */}
                                  <Row gutter={8}>
                                    <Col span={12}> <ProFormSelect name='default_workcenter_id' label='生产中心' width={120} 
                                         showSearch
                                           request={async ()=>{
                                           const x=await s_getSelectData({x_id:1,source:'workcenter'});
                                               return x.data;
                                           }} 
                                           onChange={(value)=>{
                                                // alert(value);
                                                // alert(JSON.stringify(produceCard));
                                              var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.default_workcenter_id=value;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                           }}
                                           /></Col>
                                    <Col span={12}> <ProFormSelect name='default_workgroup_id' label='生产组' width={120} 
                                         showSearch
                                         request={async ()=>{
                                         const x=await s_getSelectData({x_id:1,source:'workgroup'});
                                             return x.data;
                                         }} 
                                          onChange={(value)=>{
                                                // alert(value);
                                                // alert(JSON.stringify(produceCard));
                                              var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.default_workgroup_id=value;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                           }}
                                        /></Col>
                                  </Row>
                                  <Row gutter={8}>
                                    <Col span={12}> <ProFormDatePicker name='begindate' label='开工日期' width={120}
                                        fieldProps={{
                                          onChange(date, dateString) {
                                           var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.begindate=date;
                                                return item;
                                              });
                                              
                                              setProduceCard(t);
                                            
                                          },
                                        }}
                                    /></Col>
                                    <Col span={12}> <ProFormDatePicker name='enddate' label='完工日期' width={120}
                                        fieldProps={{
                                          onChange(date, dateString) {
                                           var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.enddate=date;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                            
                                          },
                                        }}
                                    /></Col>
                                  </Row>
                                  <ProFormRadio.Group name='dotype' label='分派类型'
                                       options={[{value:1,label:'自制'},{value:2,label:'内部备料'},
                                        {value:3,label:'自制+内部备料'}]}
                                      fieldProps={{
                                        onChange(e) {
                                          // alert(e.target.value);
                                          var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard)
                                                       item.dotype=e.target.value;
                                                return item;
                                              });
                                              // alert(JSON.stringify(t));
                                              setProduceCard(t);
                                        },
                                      }}
                                  />
                                  <Divider/>
                                  <Row gutter={8}>
                                    <Col span={12}> 
                                     <ProFormDigit name='quantity_unit' label='分派单批量' width={100}
                                         
                                               fieldProps={{
                                               onChange:async (t2)=>{
                                                var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard){
                                                       item.quantity_unit=t2;
                                                       var v=form_refProduce.current?.getFieldValue('quantity_total');
                                                        if(t2!=undefined&&t2!=0){
                                                          item.quantity_pc=Math.ceil((v?v:0)/t2);
                                                          
                                                          form_refProduce.current?.setFieldValue('quantity_pc',Math.ceil((v?v:0)/t2));
                                                          // alert(Math.ceil((v?v:0)/t2));
                                                       };
                                                   }
                                                return item;
                                              });
                                              //  alert(JSON.stringify(t));
                                              setProduceCard(t);
                                               }
                                            }}
                                            
                                        />
                                        <ProFormDigit name='quantity_total' label='分派总数' width={100}
                                            fieldProps={{
                                               onChange:async (v)=>{
                                                var t=produceCard.map((item:any)=>{
                                                if(item.card_id==selectedCard){
                                                       item.quantity_total=v;
                                                       var t2=form_refProduce.current?.getFieldValue('quantity_unit');
                                                        
                                                       if(t2!=undefined&&t2!=0){
                                                          item.quantity_pc=Math.ceil((v?v:0)/t2);
                                                          item.quantity_unit=t2;
                                                          form_refProduce.current?.setFieldValue('quantity_pc',Math.ceil((v?v:0)/t2));
                                                          // alert(Math.ceil((v?v:0)/t2));
                                                          //同步更新子件需求数量和差异
                                                        //  alert(JSON.stringify(item.material_bom));
                                                          var t3=item.material_bom.map((item2:any)=>{
                                                              var n1=item2.quantity_rate.substring(0,item2.quantity_rate.indexOf('/'));
                                                              var n2=item2.quantity_rate.substring(item2.quantity_rate.indexOf('/')+1);
                                                              item2.quantity_require=(v?v:0)*n2/n1;
                                                              item2.quantity_diff=(v?v:0)*n2/n1-item2.quantity_stock+item2.quantity_islock;
                                                              return item2; 
                                                            });
                                                           item.material_bom=t3;  
                                                           form_refProduce.current?.setFieldValue('editable_produce2',t3);
                                                          //  alert(JSON.stringify(t3));
                                                      };
                                                      return item; 
                                                   }else
                                                     return item;
                                                 
                                              });
                                              //  alert(JSON.stringify(t));
                                              setProduceCard(t);
                                               }
                                            }}
                                        />
                                       
                                    </Col>
                                    <Col span={12}>
                                         <ProFormText name='quantity_pc' label='分派单数'  width={100}
                                             
                                         />
                                         {/* <ProFormText name='print' label='打印分派单张数' width={100}
                                             placeholder={'0:所有，其他数字：批定张数'}
                                         />
                                         <Button>打印分派单</Button> */}
                                    </Col>
                                  </Row>
                                   
                              {/* </ProForm> */}
                            </Splitter.Panel>
                            <Splitter.Panel defaultSize='60%'>
                            <ProCard  style={{height:500,overflow:'auto'}}
                              extra={<Space>
                                <QueryMaterial3 setData={setMaterial} type='checkbox' x_id={1}/>
                                <Button onClick={()=>adjustQuantityRate()}>调整换算率</Button>
                                <Button onClick={()=>saveQuantityRate()}>保存换算率</Button>
                              </Space>}
                            >
                              
                              <EditableProTable<DataType2>
                                   name='editable_produce2'
                                   rowKey='rid'
                                   actionRef={action_refProduce2}
                                   editableFormRef={editable_refProduce2}
                                   search={false}
                                   options={false}
                                   columns={columns2}
                                  //dataSource={tdata2}
                                   rowSelection={{
                                        type:'checkbox',
                                     }}
                                    scroll={{y:'30vh'}}
                                   recordCreatorProps={false}
                                   editable={{
                                       type:'multiple'
                                   }}
                                  
                              />
                        </ProCard>
                            </Splitter.Panel>
                        </Splitter>
                     
                    </Splitter.Panel>
               </Splitter>
               </ProForm> 
               </ProCard>

            </Modal>

            {/* 生产申报单总配货单------------------------------------------------------------- */}
            <Modal open={openPrepare} width='90%' cancelButtonProps={{hidden:true}} 
                 okButtonProps={{hidden:true}} closable style={{top:10}}
               onCancel={()=>closePrepare()} onClose={()=>closePrepare()} destroyOnClose >
               <ProCard title='内部备料配货单' style={{height:960,overflow:'auto'}}
                  extra={<Space>
                    <Button onClick={()=>stockPrepare()}>下发配货单</Button>
                    <Button onClick={()=>printPrepare()}>打印分派配货单</Button>
                    {/* <Button onClick={()=>allocVendor(selectedPlanRecord.length>0?selectedPlanRecord[0].did:0)}>指派内部备料商</Button> */}
                    <Button onClick={()=>closePrepare()}>关闭</Button>
                  </Space>}
               >
                  <ProForm formRef={formRef_prepare} submitter={false} labelWrap
                    layout="horizontal" labelAlign="left" labelCol={{offset:0,span:8}}
                    initialValues={{
                         is_tostock:printTaskCard.fdata.length>0?printTaskCard.fdata[0].is_tostock:null,
                        //  ...commissionRec,
                        //  wfdate:commissionRec.wfdate?commissionRec.wfdate:moment(),
                    }}
                    >
                      {/* {JSON.stringify(printTaskCard.fdata.length>0?printTaskCard.fdata[0].is_tostock:null)} */}
                      <Row gutter={8}>
                        {/* <Col span={5}>
                           <ProFormSelect name='f0' label='工序卡片' width={200}
                               options={[{value:1,label:'全部'},{value:2,label:'装配'},{value:3,label:'包装'}]} />
                        </Col> */}
                        <Col span={4}>
                           <ProFormRadio.Group name='is_tostock' label='是否已下发' width={200} disabled 
                               options={[{value:0,label:'否'},{value:1,label:'是'}]}  style={{color:'red'}}/>
                        </Col>
                          {/* <Col span={4}>
                                                 <ProFormText name='vendor' label='内部备料商' width={200} />
                                                </Col>
                                                 <Col span={4}>
                                                   <ProFormText name='price' label='内部备料单价' width={120} />
                                                </Col>
                                                 <Col span={4}>
                                                   <ProFormDatePicker name='wfdate' label='实际内部备料日期' width={160} />
                                                </Col>
                                                <Col span={8}>
                                                   <ProFormText name='memo' label='备注' labelCol={{offset:0,span:3}}  />
                                                </Col> */}
                      </Row>
                      
                     <Divider>打印明细</Divider>
                        <div id='print'>
                        {
                         printTaskCard.fdata.map((item:any)=>{
                            var x=printTaskCard.tdata.filter((item2:any)=>item2.taskcard_mid==item.taskcard_id);
                          return (<>
                                   <Space id='pt' style={{display:'flex',justifyContent:'center',marginTop:66}} >
                                         <h2>华磊工贸内部备料配货单</h2>
                                   </Space>
                                   <PrintTaskCard id='pt' fdata={{...item}} tdata={x} />
                                    <div style={{pageBreakAfter:'always'}}></div>
                                  </>);
                         })
                        }
                        </div>
                  </ProForm>
               </ProCard>
            </Modal>
    </>
};

export default App;